#!/bin/bash

# 确保脚本在出错时退出
set -e

# 显示彩色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 设置绝对路径
SYNOLOGY_PATH="/volume1/docker/hello-beer-pos"

echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}   Hello Beer POS 系统群晖部署脚本 (Docker Compose版)  ${NC}"
echo -e "${GREEN}=========================================${NC}"

# 检查Docker是否已安装
if ! command -v docker &> /dev/null; then
    echo -e "${RED}错误: Docker未安装。请在群晖控制面板中安装Docker。${NC}"
    exit 1
fi

# 检查Docker Compose是否已安装
if ! command -v docker-compose &> /dev/null; then
    echo -e "${RED}错误: Docker Compose未安装。请在群晖控制面板中安装Docker Compose。${NC}"
    exit 1
fi

# 拉取最新代码
echo -e "${GREEN}拉取最新代码...${NC}"
cd $SYNOLOGY_PATH
git pull

# 创建必要的目录
echo -e "${GREEN}创建必要的目录...${NC}"
mkdir -p $SYNOLOGY_PATH/logs/nginx $SYNOLOGY_PATH/uploads $SYNOLOGY_PATH/backups $SYNOLOGY_PATH/mysql-data

# 设置目录权限
echo -e "${GREEN}设置目录权限...${NC}"
chmod -R 755 $SYNOLOGY_PATH/logs $SYNOLOGY_PATH/uploads $SYNOLOGY_PATH/backups
chmod -R 777 $SYNOLOGY_PATH/mysql-data

# 检查.env文件是否存在，如果不存在则创建
if [ ! -f "$SYNOLOGY_PATH/.env" ]; then
    echo -e "${YELLOW}未找到.env文件，创建默认配置...${NC}"
    cat > $SYNOLOGY_PATH/.env << EOF
# 数据库配置
DB_PASSWORD=Hello_Beer_2023
DB_NAME=hello_beer

# JWT配置
JWT_SECRET=j8K2p0r5Zt7xW3vA9yB6nM4cD1eF0hG

# 应用配置
NODE_ENV=production
DATABASE_URL=mysql://root:Hello_Beer_2023@db:3306/hello_beer
APP_VERSION=1.0.0

# Docker连接配置
DOCKER_HOST=unix:///var/run/docker.sock
DOCKER_SSH_USER=admin
DOCKER_SSH_PASSWORD=
DOCKER_SSH_KEY=
EOF
    echo -e "${GREEN}.env文件已创建，请根据需要修改配置${NC}"
    echo -e "${YELLOW}重要: 请编辑.env文件，配置Docker连接参数${NC}"
else
    echo -e "${GREEN}已找到.env文件，将使用现有配置${NC}"
    
    # 检查是否需要更新.env文件添加Docker配置
    if ! grep -q "DOCKER_HOST" "$SYNOLOGY_PATH/.env"; then
        echo -e "${YELLOW}更新.env文件，添加Docker连接配置...${NC}"
        cat >> $SYNOLOGY_PATH/.env << EOF

# Docker连接配置
DOCKER_HOST=unix:///var/run/docker.sock
DOCKER_SSH_USER=admin
DOCKER_SSH_PASSWORD=
DOCKER_SSH_KEY=
EOF
    fi
fi

# 构建前端静态文件
echo -e "${GREEN}构建前端静态文件...${NC}"
if [ -d "$SYNOLOGY_PATH/frontend" ]; then
  cd $SYNOLOGY_PATH/frontend
  if [ -f "package.json" ]; then
    # 检查dist目录是否存在
    if [ -d "$SYNOLOGY_PATH/frontend/dist" ] && [ "$(ls -A $SYNOLOGY_PATH/frontend/dist)" ]; then
      echo -e "${GREEN}前端构建文件已存在，跳过构建步骤${NC}"
    else
      echo -e "${YELLOW}安装前端依赖...${NC}"
      npm install
      
      echo -e "${YELLOW}构建前端静态文件...${NC}"
      npx vite build
    fi
    
    cd $SYNOLOGY_PATH
  else
    echo -e "${RED}警告: 前端目录中没有找到package.json文件，跳过前端构建${NC}"
  fi
else
  echo -e "${RED}警告: 未找到前端目录，跳过前端构建${NC}"
fi

# 停止并删除现有容器
echo -e "${YELLOW}停止并删除现有容器...${NC}"
docker-compose -f docker-compose.mount.yml down

# 修改docker-compose.mount.yml文件，添加Docker socket挂载
echo -e "${GREEN}更新Docker Compose配置...${NC}"
cat > $SYNOLOGY_PATH/docker-compose.mount.yml << EOF
version: '3'

services:
  # MySQL数据库
  db:
    image: mysql:8.0
    container_name: hello-beer-db
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: \${DB_PASSWORD}
      MYSQL_DATABASE: \${DB_NAME}
      MYSQL_USER: hello_beer_user
      MYSQL_PASSWORD: \${DB_PASSWORD}
    volumes:
      - ./mysql-data:/var/lib/mysql
    ports:
      - "3306:3306"
    command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    networks:
      - hello-beer-network

  # 后端服务 - 使用挂载方式
  backend:
    build:
      context: .
      dockerfile: Dockerfile.backend.mount.slim
    container_name: hello-beer-backend
    restart: always
    depends_on:
      - db
    environment:
      - NODE_ENV=\${NODE_ENV}
      - DATABASE_URL=\${DATABASE_URL}
      - PORT=3100
      - JWT_SECRET=\${JWT_SECRET}
      - DOCKER_HOST=unix:///var/run/docker.sock
    volumes:
      - ./backend:/app
      - ./.env:/app/.env
      - ./logs:/app/logs
      - ./uploads:/app/uploads
      - ./backups:/app/backups
      - /var/run/docker.sock:/var/run/docker.sock
    ports:
      - "3100:3100"
    networks:
      - hello-beer-network

  # 前端服务 - 使用挂载方式
  frontend:
    build:
      context: .
      dockerfile: Dockerfile.frontend.mount.slim
    container_name: hello-beer-frontend
    restart: always
    depends_on:
      - backend
    volumes:
      - ./frontend/dist:/usr/share/nginx/html
      - ./nginx/conf.d:/etc/nginx/conf.d
      - ./logs/nginx:/var/log/nginx
    ports:
      - "8081:80"
    networks:
      - hello-beer-network

networks:
  hello-beer-network:
    driver: bridge 
EOF

# 构建并启动容器
echo -e "${GREEN}构建并启动容器...${NC}"
docker-compose -f docker-compose.mount.yml up -d --build

# 检查容器状态
echo -e "${GREEN}检查容器状态:${NC}"
docker-compose -f docker-compose.mount.yml ps

# 获取服务器IP地址，使用更可靠的方法
SERVER_IP=$(ip route get 1 | awk '{print $NF;exit}' 2>/dev/null || hostname -I | awk '{print $1}' 2>/dev/null || echo "服务器IP")

# 完成
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}   部署完成!   ${NC}"
echo -e "${GREEN}=========================================${NC}"
echo -e "${YELLOW}前端访问地址: http://${SERVER_IP}:8081${NC}"
echo -e "${YELLOW}后端API地址: http://${SERVER_IP}:3100${NC}"

echo -e "${GREEN}部署已完成，但还未恢复数据库。如需恢复数据库，请上传backup-full.sql并执行:${NC}"
echo -e "${YELLOW}docker cp backup-full.sql hello-beer-db:/tmp/${NC}"
echo -e "${YELLOW}docker exec hello-beer-db sh -c 'mysql -u root -p\"\${DB_PASSWORD}\" \${DB_NAME} < /tmp/backup-full.sql'${NC}"

# 显示后端日志
echo -e "${GREEN}显示后端日志（按Ctrl+C退出）:${NC}"
docker-compose -f docker-compose.mount.yml logs -f backend 